package vote.service.Impl;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.RedirectView;
import vote.config.WxMpProperties;
import vote.service.UserService;
import vote.service.WxService;
import vote.util.BusinessException;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 * Author:han
 * Date: 2024-05-21
 */
@Service
@Slf4j
public class WxServiceImpl implements WxService {
    @Resource
    private WxMpProperties wxProperties;
    @Resource
    private UserService userService;
    @Resource
    private WxMpService wxService;
    @Override
    public String login(String callback, HttpServletResponse response) {
        String URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        return String.format(URL, wxProperties.getConfigs().get(0).getAppId(), URLEncoder.encode(callback + "/wx/callback"), "UTF-8");
    }

    @SneakyThrows
    @Override
    public RedirectView solveCallback(String code) {
        log.info(code);
        try {
            WxOAuth2AccessToken accessToken = wxService.getOAuth2Service().getAccessToken(code);
            WxOAuth2UserInfo userInfo = wxService.getOAuth2Service().getUserInfo(accessToken, "zh_CN");
             userService.auth(userInfo);
        } catch (Exception e) {
            log.error("callBack error", e);
        }
        RedirectView redirectView = new RedirectView();
        redirectView.setUrl("https://mp.weixin.qq.com/s/jaeHfQSCfixHGr73Ekcr6w");
        return redirectView;
    }
    public Map<String, String> getGenerateSignatureParams(HttpServletRequest request, boolean isBase) {
        HashMap<String, String> map = new HashMap<>(8);
        map.put("openid", request.getParameter("openid"));
        map.put("appid", request.getParameter("appid"));
        map.put("source", request.getParameter("source"));
        map.put("time", request.getParameter("time"));
        if (!isBase) {
            map.put("nickname", request.getParameter("nickname"));
            map.put("headimg", request.getParameter("headimg"));
        }
        return map;
    }
}
